/**
 * 
 */
package ae.pcfc.cldos.online.web.controller.client.company.visa.edit;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ws.client.WebServiceIOException;
import org.springframework.ws.soap.client.SoapFaultClientException;

import ae.pcfc.cldos.online.common.ConstantsCommon.Steps;
import ae.pcfc.cldos.online.common.delegate.CompanyInformationDelegate;
import ae.pcfc.cldos.online.common.delegate.EmploymentVisaDelegate;
import ae.pcfc.cldos.online.common.delegate.FnpGSDelegate;
import ae.pcfc.cldos.online.common.exception.EmployeeAllreadyExistException;
import ae.pcfc.cldos.online.common.exception.EmployeeIsBanedException;
import ae.pcfc.cldos.online.common.exception.FNPAppException;
import ae.pcfc.cldos.online.common.exception.GSAppException;
import ae.pcfc.cldos.online.common.exception.InsufficientBGException;
import ae.pcfc.cldos.online.common.exception.InvalidClientException;
import ae.pcfc.cldos.online.common.exception.LicenseErrorRemarkException;
import ae.pcfc.cldos.online.common.exception.LicenseExpiredException;
import ae.pcfc.cldos.online.common.exception.NoSuchCompanyException;
import ae.pcfc.cldos.online.common.exception.PaymentException;
import ae.pcfc.cldos.online.common.exception.QoutaAllowedException;
import ae.pcfc.cldos.online.common.exception.QoutaReqAllowedException;
import ae.pcfc.cldos.online.common.exception.RequestAllreadyExistException;
import ae.pcfc.cldos.online.common.exception.UltimusAppException;
import ae.pcfc.cldos.online.common.exception.UpdateClientDtlException;
import ae.pcfc.cldos.online.common.vo.AppSaveResponseVO;
import ae.pcfc.cldos.online.common.vo.CommentsVO;
import ae.pcfc.cldos.online.common.vo.CompanyInformationVO;
import ae.pcfc.cldos.online.common.vo.EmployeVisaVO;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.common.vo.employee.details.AddressDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.EmployeeDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PassportDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PersonalDetailsVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPCatalogVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPParameterVO;
import ae.pcfc.cldos.online.gs.ConstantsGS;
import ae.pcfc.cldos.online.web.Constants;
import ae.pcfc.cldos.online.web.PageType;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.ViewUtils;
import ae.pcfc.cldos.online.web.controller.base.BaseNewVisaController;
import ae.pcfc.cldos.online.web.model.CompanyInformationModel;
import ae.pcfc.cldos.online.web.model.EmploymentVisaLicenseInfo;
import ae.pcfc.cldos.online.web.model.FilesIncomingBean;
import ae.pcfc.cldos.online.web.services.breadcrumbs.BreadCrumbsFactoryService;
import ae.pcfc.cldos.online.web.services.fnp.FnpParametersCheckService;

/**
 * @author Abed
 *
 */
@Controller
@RequestMapping(value = ViewPath.__COMPANY_EMPLOYMENT_VISA_EDIT)
public class CompanyEmploymentVisaEditController extends BaseNewVisaController{
	
	@Autowired
	@Qualifier("employmentVisaDelegate")
	private EmploymentVisaDelegate employmentVisaDelegate;
	
	@Autowired
	@Qualifier("companyInformationDelegate")
	private CompanyInformationDelegate companyInformationDelegate;
	
	private FnpGSDelegate FnpGSDelegate;
	@Resource(name = "FnpGSDelegate")
	public void setFnpGSDelegate(FnpGSDelegate FnpGSDelegate) {
		this.FnpGSDelegate = FnpGSDelegate;
	}
	
	@Autowired
	private FnpParametersCheckService fnpParametersCheckService;
	
	
	@SuppressWarnings("unchecked")
	@ModelAttribute(Constants.__COMPANY_EMPLOYMENT_VISA_REGISTRATION_LICENSE_INFO_REQUEST_MODEL_KEY)
	public EmploymentVisaLicenseInfo populateRegisterEmploymentVisaEditInfoModel(@RequestParam(required=true) String appId,
			HttpServletRequest request, ModelMap model) throws Exception {
		EmploymentVisaLicenseInfo employmentVisaInfo = new EmploymentVisaLicenseInfo();
		
		EmployeVisaVO employeVisaVO = employmentVisaDelegate.getEmployeeVisaDetailByAppId(
				encryptionDelegate.decodeAndDecrypt(appId), getUserVO(), Steps.RESUBMIT);
		
		AddressDetailsVO addressDetailsVO = employeVisaVO.getAddressDetailsVO();
		mapper.map(addressDetailsVO, employmentVisaInfo);
		CommentsVO commentsVO = employeVisaVO.getCommentsVO();
		mapper.map(commentsVO, employmentVisaInfo);
		EmployeeDetailsVO employeeDetailsVO = employeVisaVO.getEmployeeDetailsVO();
		mapper.map(employeeDetailsVO, employmentVisaInfo);
		PassportDetailsVO passportDetailsVO = employeVisaVO.getPassportDetailsVO();
		mapper.map(passportDetailsVO, employmentVisaInfo);
		PersonalDetailsVO personalDetailsVO = employeVisaVO.getPersonalDetailsVO();
		mapper.map(personalDetailsVO, employmentVisaInfo);
		
		List<FileVO> fileVOList = employeVisaVO.getFileVOList();
		System.out.println(fileVOList);
		model.put("files", fileVOList);
		model.put("comments", employeVisaVO.getApplicationCommentVOs());
		
		List<FNPCatalogVO> fnpCatalogs = null;
		
		if(securityService.isCompanyAdmin()){
			String empSourceParam = request.getParameter(Constants.__EMP_SOURCE_PARAM);
			empSourceParam = employmentVisaInfo.getEmployeeSource().toString();
			model.put("bgRequired", ConstantsGS.__BG_EMP_VISA);
			fnpCatalogs = FnpGSDelegate.getFnpCatalogVOsByServiceCode(empSourceParam);
		} else {
			fnpCatalogs = Collections.EMPTY_LIST;
		}
		
		model.put(Constants.__FNP_CATALOG_MODEL_KEY, fnpCatalogs);
		model.put("appId", appId);
		return employmentVisaInfo;
	}
	
	@ModelAttribute
	public void populateBreadCrumbs(ModelMap model, @RequestParam String appId) {
		breadCrumbsFactoryService.populateMainAdminRewiewBreadcrumb(model, appId, BreadCrumbsFactoryService.TASK_TYPE_RESUBMIT);
	}

	/**
	 * @param request
	 * @param model
	 * @param employmentVisaLicenseInfo
	 * @return
	 * @throws NoSuchCompanyException 
	 */
	@ModelAttribute("CompanyInformationInfo")
	public CompanyInformationModel populateCompanyInformationInfoModel(HttpServletRequest request){
		CompanyInformationModel companyInformationModel = new CompanyInformationModel();
		CompanyInformationVO companyInformationVO=null;
		try{
			companyInformationVO = companyInformationDelegate.retriveGSInformation(getUserVO());
			mapper.map(companyInformationVO, companyInformationModel);
		}catch(NoSuchCompanyException e){
			companyInformationModel.setCompanyError(true);
		}catch(GSAppException e){
			companyInformationModel.setGsError(true);
		}
		try{
			companyInformationVO = companyInformationDelegate.retriveFNPInformation(getUserVO());
			companyInformationModel.setPrepaidAccBalance(new Double(companyInformationVO.getPrepaidAccBalance()).toString());
			companyInformationModel.setReservedAccBalance(new Double(companyInformationVO.getReservedAccBalance()).toString());
		}catch(NoSuchCompanyException e){
			companyInformationModel.setCompanyError(true);
		}catch(FNPAppException e){
			companyInformationModel.setFnpError(true);
		}
		return companyInformationModel;
	}
		
	
	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void show(@RequestParam(required=true) String appId, ModelMap model) {
		model.put("appId", appId);
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public ModelAndView form(
			HttpServletRequest request,
			@RequestParam String appId,
			@RequestParam(required=false) String fnpServiceCode,
			//SessionStatus status,
			@ModelAttribute @Valid FilesIncomingBean filesIncomingBean,
			BindingResult fileErrors,
			@ModelAttribute(value = Constants.__COMPANY_EMPLOYMENT_VISA_REGISTRATION_LICENSE_INFO_REQUEST_MODEL_KEY) @Valid EmploymentVisaLicenseInfo employmentVisaLicenseInfo,
			BindingResult errors) throws Exception {
		ModelAndView mav = null;
		List<FNPParameterVO> allParams = null;
		if(securityService.isCompanyAdmin() && (fnpServiceCode==null || fnpServiceCode.isEmpty())){
			errors.reject("no.payment.code");
		} else if(securityService.isCompanyAdmin()){
			allParams = FnpGSDelegate.retreiveFNPParameters(Arrays.asList(new String[]{fnpServiceCode}));
			List<FNPParameterVO> notFeeled = fnpParametersCheckService.feelParamsAndGetNotFeeled(request, allParams);
			if(notFeeled.size()>0){
				errors.reject("sdgsd", "Recomplete payment info please");
			}
		}
		
		if (errors.hasErrors() || fileErrors.hasErrors()) {
			
			System.out.println("there is errors : " );
			for(ObjectError error : errors.getAllErrors())
			{
				System.out.println(error.getCode() + " " + error.getDefaultMessage());
			}

			mav =  ViewUtils.DEFAULT_VIEW;

		}else{
			EmployeeDetailsVO employeeDetailsVO = new EmployeeDetailsVO();
			mapper.map(employmentVisaLicenseInfo, employeeDetailsVO);
			PassportDetailsVO passportDetailsVO = new PassportDetailsVO();
			mapper.map(employmentVisaLicenseInfo, passportDetailsVO);
			PersonalDetailsVO personalDetailsVO = new PersonalDetailsVO();
			mapper.map(employmentVisaLicenseInfo, personalDetailsVO);
			AddressDetailsVO addressDetailsVO = new AddressDetailsVO();
			mapper.map(employmentVisaLicenseInfo, addressDetailsVO);
			CommentsVO commentsVO = new CommentsVO();
			mapper.map(employmentVisaLicenseInfo, commentsVO);
			
			EmployeVisaVO employeVisaVO = new EmployeVisaVO();
			employeVisaVO.setAddressDetailsVO(addressDetailsVO);
			employeVisaVO.setCommentsVO(commentsVO);
			employeVisaVO.setEmployeeDetailsVO(employeeDetailsVO);
			employeVisaVO.setPassportDetailsVO(passportDetailsVO);
			employeVisaVO.setPersonalDetailsVO(personalDetailsVO);
			employeVisaVO.setFileVOList(getFileVOList(filesIncomingBean));
			employeVisaVO.setUserVO(getUserVO());
			
			
			employeVisaVO.setFnpServiceCode(fnpServiceCode);
			employeVisaVO.setFnpParams(allParams);
			String refNo = null;
			String incidentNo = null;
			try{
				AppSaveResponseVO appSaveResponseVO = employmentVisaDelegate.reSubmit(employeVisaVO, encryptionDelegate.decodeAndDecrypt(appId));
				refNo = appSaveResponseVO.getReferenceNo();
				incidentNo = appSaveResponseVO.getIncidentNo();
			} catch (PaymentException e) {
				errors.reject("error.payment");
			}catch (LicenseErrorRemarkException e) {
				errors.reject("license.errorremark");
			}catch (LicenseExpiredException e) {
				errors.reject("license.expire");
			} catch (EmployeeAllreadyExistException e) {
				errors.reject("employee.exist");
			} catch (RequestAllreadyExistException e) {
				errors.reject("request.exist");
			} catch (EmployeeIsBanedException e) {
				errors.reject("employee.baned");
			}catch (QoutaAllowedException e) {
				errors.reject("act.emp.more.than.allowed");
			}catch (QoutaReqAllowedException e) {
				errors.reject("act.emp.more.than.reqallowed");
			}catch(InsufficientBGException e){
				errors.reject("insufficient.bg");
			}catch(InvalidClientException e){
				errors.reject("invalid.client");
			}catch(UpdateClientDtlException e){
				errors.reject("update.client.dtls");
			}catch(GSAppException e){
				errors.reject("unable.to.proceed.gs.down");
			}catch(UltimusAppException e){
				errors.reject("unable.to.proceed.ultimus.down");
			}catch(WebServiceIOException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.gs.fnp.down");
			}catch(SoapFaultClientException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.gs.fnp.down");
			}catch(Exception e){
				e.printStackTrace();
				errors.reject("unable.to.proceed");
			}
			
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put(Constants.__REFRENCE_NO, refNo);
			if(incidentNo!=null){
				paramMap.put(Constants.__INCIDENT_NO, incidentNo);
			}
			
			if(errors.hasErrors()){
				mav =  ViewUtils.DEFAULT_VIEW;
			}else{
				mav = new ModelAndView(ViewUtils.getRedirect(ViewPath.__CONFIRMATION, PageType.SHOW, paramMap));
			}

		}
		return mav;
	}

}
